//
//  BackLogDetailViewController.m
//  代办事宜
//
//  Created by wang on 12-8-22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "BackLogDetailViewController.h"
#import "TSActionSheet.h"
#import "TSPopoverController.h"
#import "DealWithBackLogViewController.h"
#import "BackOffBackLogViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"

@interface BackLogDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate,ASIHTTPRequestDelegate,UIWebViewDelegate>

@property(strong,nonatomic) UITableView* myDetailView;
@property(strong,nonatomic)  BackOffBackLogViewController*backOffView;
@property(strong,nonatomic) UIWebView*tempWebview4annex;

@end

@implementation BackLogDetailViewController

@synthesize myDetailView=_myDetailView;
@synthesize backOffView=_backOffView;
@synthesize tempWebview4annex=_tempWebview4annex;
NSDictionary* totalDictory;
NSArray* eventDetailArray;
ASIFormDataRequest *requestBackOff;
ASIFormDataRequest*requestActionId;
NSArray* arrayBackOff;
NSDictionary*actionIdInfo;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title=@"审批明细";
    self.view.contentMode = UIViewContentModeScaleAspectFill;
     UIBarButtonItem *topRightButton = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStyleBordered target:self action:@selector(showActionSheet:forEvent:)];
    self.navigationItem.rightBarButtonItem = topRightButton;
    self.myDetailView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 
                                                                     self.view.bounds.size.height)
                                                    style:UITableViewStylePlain];      
    [self.myDetailView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.myDetailView setDelegate:self];
    [self.myDetailView setDataSource:self];
    [self.myDetailView setEditing:NO animated:NO];
    [self.view addSubview: self.myDetailView];
}


-(void) viewWillAppear:(BOOL)animated {
    
    NSString* u=[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"];
    NSURL *url = [NSURL URLWithString:u];    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];    
    [request addPostValue: @"getEventDetailListAndSort" forKey:@"method"];
    [request addPostValue: [totalDictory objectForKey:@"eventId"] forKey:@"eventId"];
    [request setDelegate:self];
    [request start];
    
    //预先加载回退处理人
    NSString* u2=[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"];
    NSURL *url2= [NSURL URLWithString:u2];    
    requestBackOff = [ASIFormDataRequest requestWithURL:url2];    
    [requestBackOff addPostValue: @"getRollbackEventDetailList" forKey:@"method"];
    [requestBackOff addPostValue: [totalDictory objectForKey:@"eventId"] forKey:@"eventId"];//
    [requestBackOff setDelegate:self];
    [requestBackOff start];
    
    //获取总单actionId信息
    NSString* u3=[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"];
    NSURL *url3= [NSURL URLWithString:u3];    
    requestActionId = [ASIFormDataRequest requestWithURL:url3];    
    [requestActionId addPostValue: @"getEventTotalById" forKey:@"method"];
    [requestActionId addPostValue: [totalDictory objectForKey:@"eventId"] forKey:@"eventId"];//
    [requestActionId setDelegate:self];
    [requestActionId start];
    
    [self showMbprogress];

}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return [NSString stringWithFormat:@"Title：%@",[totalDictory objectForKey:@"eventTitle"]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [eventDetailArray count];
}

//row高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row==0){
        return 600;
    }else {
            return 140;
        }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString* CellIdentifier = [NSString stringWithFormat:@"%d%d",indexPath.section, indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    for (UIView *v in [cell subviews]) {
        if ([v isKindOfClass:[UILabel class]] |
            [v isKindOfClass:[UITextView class]]) {
            [v removeFromSuperview];
        }
    }   
    //事务处理人
    UILabel*tempLabel4operator = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 400, 30)];
    NSUInteger index = [indexPath row];
    NSDictionary*detail=[eventDetailArray objectAtIndex:index];
    
    if(index==0)
    {
        [tempLabel4operator setText:[[NSString alloc] initWithFormat:@"发起人：%@",[detail objectForKey:@"userName"]]];
    }else {
        
        [tempLabel4operator setText:[[NSString alloc] initWithFormat:@"处理人：%@",[detail objectForKey:@"userName"]]];
    }
    tempLabel4operator.font = [UIFont systemFontOfSize:20];
    [tempLabel4operator setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
    [tempLabel4operator setBackgroundColor:[UIColor clearColor]];
    [cell addSubview:tempLabel4operator];
    
    //职位
    UILabel*tempLabel4position = [[UILabel alloc] initWithFrame:CGRectMake(450, 10, 500, 30)];
    [tempLabel4position setText:[[NSString alloc] initWithFormat:@"职位：%@",[detail objectForKey:@"roleName"]!=nil?[detail objectForKey:@"roleName"]:@""]];
    tempLabel4position.font = [UIFont systemFontOfSize:20];
    [tempLabel4position setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
    [tempLabel4position setBackgroundColor:[UIColor clearColor]];
    [cell addSubview:tempLabel4position];
    
    if(indexPath.row==0){
        
        //获取内容url
        NSString*contenturl;
        if([[actionIdInfo objectForKey:@"uiXmlFlag"] isEqualToString:@"Y"])
        {
            contenturl=[NSString stringWithFormat:@"%@eventId=%@&subFolders=%@&NFSQID=IPhone",[[NSUserDefaults standardUserDefaults]objectForKey:@"xmlContentUrl"],[actionIdInfo objectForKey:@"eventId"],[actionIdInfo objectForKey:@"subFolders"]];
            
        }else if([[actionIdInfo objectForKey:@"uiXmlFlag"] isEqualToString:@"N"])
        {
            NSRange a= [[actionIdInfo objectForKey:@"actionId"] rangeOfString:@"?"];
            int len=a.length;

            if(len==0){
                contenturl=[NSString stringWithFormat:@"%@?type=view&XMLId=%@&xmlFolder=%@&NFSQID=IPhone",[actionIdInfo objectForKey:@"actionId"],[actionIdInfo objectForKey:@"eventId"],[actionIdInfo objectForKey:@"subFolders"]];
            }else {
                contenturl=[NSString stringWithFormat:@"%@&iid=0&event_id=%@&xmlFolder=%@&NFSQID=IPhone",[actionIdInfo objectForKey:@"actionId"],[actionIdInfo objectForKey:@"eventId"],[actionIdInfo objectForKey:@"subFolders"]];
            }
            
        }
        
        NSMutableString *urlSearch = [NSMutableString stringWithFormat:contenturl]; 
        UIWebView*tempWebview4content =[[UIWebView alloc] initWithFrame:CGRectMake(10, 50, 720, 400)];
        [tempWebview4content setScalesPageToFit:YES];
        [tempWebview4content loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[urlSearch stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
        [cell addSubview:tempWebview4content];
        
        //备注
        UILabel*tempLabel4remark = [[UILabel alloc] initWithFrame:CGRectMake(10, 490, 700, 35)];
        [tempLabel4remark setText:[[NSString alloc] initWithFormat:@"备注    ：%@",[detail objectForKey:@"memo"]]];
        [tempLabel4remark setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
        tempLabel4remark.font = [UIFont systemFontOfSize:20];
        [tempLabel4remark setBackgroundColor:[UIColor clearColor]];
        tempLabel4remark.lineBreakMode = UILineBreakModeWordWrap; 
        tempLabel4remark.numberOfLines = 0;
        [tempLabel4remark sizeToFit];
        [cell addSubview:tempLabel4remark];
        
        //附件
        UILabel*tempLabel4annex = [[UILabel alloc] initWithFrame:CGRectMake(10, 450, 100, 35)];
        [tempLabel4annex setText:[[NSString alloc] initWithFormat:@"附件    ："]];
        [tempLabel4annex setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
        tempLabel4annex.font = [UIFont systemFontOfSize:20];
        [tempLabel4annex setBackgroundColor:[UIColor clearColor]];
        [cell addSubview:tempLabel4annex];
        
        //附件url
        self.tempWebview4annex =[[UIWebView alloc] initWithFrame:CGRectMake(100, 458, 250, 35)];
        self.tempWebview4annex.delegate=self;
        [self.tempWebview4annex setScalesPageToFit:YES];
        [[[self.tempWebview4annex subviews] objectAtIndex:0] setScrollEnabled:NO];//禁用scroll
        NSString*htmlStr=[[NSString alloc] initWithFormat:@"<font size=10>%@</font>",[detail objectForKey:@"link"]];
        [self.tempWebview4annex loadHTMLString:htmlStr baseURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"fliePathUrl"]]];
        [cell addSubview:self.tempWebview4annex];
    
    }else {
        //操作状态
        UILabel*tempLabel4operaState = [[UILabel alloc] initWithFrame:CGRectMake(10, 38, 400, 30)];
        NSString* stateString;
        if([[detail objectForKey:@"operation"] isEqualToString:@"1"]){
            stateString=@"同意";
        }else {
            stateString=@"未处理";
        }
        [tempLabel4operaState setText:[[NSString alloc] initWithFormat:@"状态    ：%@",stateString]];
        [tempLabel4operaState setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
        tempLabel4operaState.font = [UIFont systemFontOfSize:20];
        [tempLabel4operaState setBackgroundColor:[UIColor clearColor]];
        [cell addSubview:tempLabel4operaState];
        
        //事务处理时间
        UILabel*tempLabel4operatDate = [[UILabel alloc] initWithFrame:CGRectMake(450, 38, 400, 30)];
        [tempLabel4operatDate setText:[[NSString alloc] initWithFormat:@"时间：2012-08-01 12:30"]];
        tempLabel4operatDate.font = [UIFont systemFontOfSize:20];
        [tempLabel4operatDate setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
        [tempLabel4operatDate setBackgroundColor:[UIColor clearColor]];
        [cell addSubview:tempLabel4operatDate];
        
        //意见
        UILabel*tempLabel4suggest = [[UILabel alloc] initWithFrame:CGRectMake(10, 70, 800, 30)];
        [tempLabel4suggest setText:[[NSString alloc] initWithFormat:@"意见    ：%@",[detail objectForKey:@"memo"]!=nil?[detail objectForKey:@"memo"]:@""]];
        [tempLabel4suggest setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
        tempLabel4suggest.font = [UIFont systemFontOfSize:20];
        [tempLabel4suggest setBackgroundColor:[UIColor clearColor]];
        tempLabel4suggest.lineBreakMode = UILineBreakModeWordWrap; 
        tempLabel4suggest.numberOfLines = 0;
        [tempLabel4suggest sizeToFit];
        [cell addSubview:tempLabel4suggest];
        
        //附件
        UILabel*tempLabel4annex = [[UILabel alloc] initWithFrame:CGRectMake(10, 110, 100, 35)];
        [tempLabel4annex setText:[[NSString alloc] initWithFormat:@"附件    ："]];
        [tempLabel4annex setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
        tempLabel4annex.font = [UIFont systemFontOfSize:20];
        [tempLabel4annex setBackgroundColor:[UIColor clearColor]];
        [cell addSubview:tempLabel4annex];
        
        //附件url
        self.tempWebview4annex =[[UIWebView alloc] initWithFrame:CGRectMake(100, 115, 250, 20)];
        self.tempWebview4annex.delegate=self;
        [[[self.tempWebview4annex subviews] objectAtIndex:0] setScrollEnabled:NO];//禁用scroll
        [self.tempWebview4annex setScalesPageToFit:YES];
        NSString*htmlStr=[[NSString alloc] initWithFormat:@"<body bgColor=lightgray><font size=10>%@</font></body",[detail objectForKey:@"link"]];
        [self.tempWebview4annex loadHTMLString:htmlStr baseURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"fliePathUrl"]]];
        [cell addSubview:self.tempWebview4annex];
        
        UIImage* backImg = [UIImage imageNamed:@"tableviewcell.png"];
        UIImageView *backImgView =[[UIImageView alloc] initWithImage:backImg];
        [cell setBackgroundView:backImgView];
    }
    

    return cell;
    
}

//popover
-(void)showPopover:(id)sender forEvent:(UIEvent*)event
{
    UITableViewController *tableViewController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
    tableViewController.view.frame = CGRectMake(0,0, 320, 400);
    TSPopoverController *popoverController = [[TSPopoverController alloc] initWithContentViewController:tableViewController];
    popoverController.cornerRadius = 5;
    popoverController.titleText = @"change order";
    popoverController.popoverBaseColor = [UIColor lightGrayColor];
    popoverController.popoverGradient= NO;
    [popoverController showPopoverWithTouch:event];
    
}

-(void) showActionSheet:(id)sender forEvent:(UIEvent*)event
{
    TSActionSheet *actionSheet = [[TSActionSheet alloc] initWithTitle:@"代办事宜"];
    [actionSheet destructiveButtonWithTitle:@"处理" block:^{
      NSLog(@"pushed 处理");
        DealWithBackLogViewController*dealWithView=[[DealWithBackLogViewController alloc] init];
        [dealWithView passEventObjFromDetail:totalDictory];
        [self.navigationController pushViewController:dealWithView animated:YES];
    }];
    
    //固定流程有回退功能，人意流程木有
    if(![[totalDictory objectForKey:@"anyFlag"] isEqualToString:@"Y"]){
    [actionSheet addButtonWithTitle:@"回退" block:^{
        NSLog(@"pushed 回退");

        self.backOffView=[[BackOffBackLogViewController alloc] initWithFrame:CGRectMake(15, 300, self.view.bounds.size.width-30, 400)];
        [self.backOffView passBackOffFromSuperView:arrayBackOff];
        [self.view addSubview:self.backOffView]; 
    }];
    }
    [actionSheet cancelButtonWithTitle:@"Cancel" block:nil];
    actionSheet.cornerRadius = 5;
    [actionSheet showWithTouch:event];

}


-(void)passFromtotal:(NSDictionary*)total{
    totalDictory=total;
}



- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    
    NSError *error = [request error];
    //回退处理人请求
    if(request==requestBackOff){
        if (!error) {
            NSString *res = [request responseString];
            arrayBackOff= [res objectFromJSONString];
        }   
    }else if (request==requestActionId) {
        if (!error) {
            NSString *res = [request responseString];
            actionIdInfo= [res objectFromJSONString];
        }    
    }else{
    if (!error) {
        NSString *res = [request responseString];
        eventDetailArray= [res objectFromJSONString];
    }    
    [self.myDetailView reloadData];
    }
    [self hideMbProgress];

}

-(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    if(navigationType==UIWebViewNavigationTypeLinkClicked)
    {
        [webView stopLoading];
    [[UIApplication sharedApplication] openURL:[request URL]];
    }
    return YES;
}
@end
